package com.yupi.yuoj.judge;

import cn.hutool.json.JSONUtil;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.exception.BusinessException;
import com.yupi.yuoj.judge.codesandbox.CodeSandbox;
import com.yupi.yuoj.judge.codesandbox.CodeSandboxFactory;
import com.yupi.yuoj.judge.codesandbox.CodeSandboxProxy;
import com.yupi.yuoj.judge.codesandbox.model.ExecuteCodeRequest;
import com.yupi.yuoj.judge.codesandbox.model.ExecuteCodeResponse;
import com.yupi.yuoj.judge.strategy.JudgeContext;
import com.yupi.yuoj.model.dto.question.JudgeCase;
import com.yupi.yuoj.model.entity.Question;
import com.yupi.yuoj.model.entity.QuestionSubmit;
import com.yupi.yuoj.model.enums.QuestionSubmitStatusEnum;
import com.yupi.yuoj.judge.codesandbox.model.JudgeInfo;
import com.yupi.yuoj.service.QuestionService;
import com.yupi.yuoj.service.QuestionSubmitService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: wenjupeng
 * @Date: 2025/01/18/18:03
 * @Description:
 * @Param:
 * @return:
 */
@Service
public class JudgeServiceImpl implements JudgeService {
   @Resource
   private QuestionService questionService;
   @Resource
   private QuestionSubmitService questionSubmitService;
   
   @Resource
   private JudgeManager judgeManager;
    @Value("${codesandbox.type:example}")
    private String type;
   @Override
    public QuestionSubmit doJudge(long questionSubmitId) {
        //判题服务业务流程：
        //1) 传入题目的提交id，获取到对应的题目、提交信息（包含代码、编程语言等）
        //根据题目提交信息拿到题目信息
        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);
        if(questionSubmit == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"提交信息不存在");
        }
        //questionId : 题目id
        Long questionId = questionSubmit.getQuestionId();
        //根据题目id查询题目
        Question question = questionService.getById(questionId);
        //如果题目为空。。。。
        if(question == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"题目不存在");
        }
        //2)如果不为等待状态
        if(!questionSubmit.getStatus().equals(QuestionSubmitStatusEnum.WAITING.getValue())){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"题目正在判题中，无需重复提交");
        }
        //3)否则修改状态--->更改判题（题目提交）的状态为“判题中”<假如题目已经在判题中了，但是还没有判完，所有需要修改状态，避免重复提交判题>，防止重复执行，也能让用户及时看到状态。
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
        boolean update = questionSubmitService.updateById(questionSubmitUpdate);
        if(!update){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"题目状态更新错误");
        }
        //4）调用沙箱，获取到执行结果
       CodeSandbox codeSandbox = CodeSandboxFactory.newInstance(type);
       codeSandbox = new CodeSandboxProxy(codeSandbox);
       String language = questionSubmit.getLanguage();
       String code = questionSubmit.getCode();
       //获取输入用例（没有看懂stream流）
       String judgeCaseStr = question.getJudgeCase();
       List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCaseStr, JudgeCase.class);
       //获取lambada表达式，把每一个输入拼成一个列表-->得到所有的输入列表
       List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());
       ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
               .code(code)
               .language(language)
               .inputList(inputList)
               .build();
       ExecuteCodeResponse executeCodeResponse = codeSandbox.executeCode(executeCodeRequest);
       //拿到判题的输出
       List<String> outputList = executeCodeResponse.getOutputList();
       //5）根据沙箱的执行结果，设置题目的判题状态和信息
       JudgeContext judgeContext = new JudgeContext();
       judgeContext.setJudgeInfo(executeCodeResponse.getJudgeInfo());
       judgeContext.setInputList(inputList);
       judgeContext.setOutputList(outputList);
       judgeContext.setJudgeCaseList(judgeCaseList);
       judgeContext.setQuestion(question);
       judgeContext.setQuestionSubmit(questionSubmit);
       JudgeInfo judgeInfo = judgeManager.doJudge(judgeContext);
       //6)修改数据库中的判题结果
       questionSubmitUpdate = new QuestionSubmit();
       questionSubmitUpdate.setId(questionSubmitId);
       questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.SUCCEED.getValue());
       //根据判题服务得到的判题结果
       questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
       update = questionSubmitService.updateById(questionSubmitUpdate);
       if(!update){
           throw new BusinessException(ErrorCode.OPERATION_ERROR,"题目状态更新错误");
       }
       //判题成功过后，返回的话，再从数据库查询一次
       QuestionSubmit questionSubmitResult = questionSubmitService.getById(questionId);
       return questionSubmitResult;

 }
}
